package com.study.lxy.zookeeper;

import com.study.lxy.zookeeper.utils.consts.CommonConsts;
import org.apache.commons.lang3.StringUtils;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.util.Map;
import java.util.Properties;

public class AppRun {
    private static final Logger logger = LoggerFactory.getLogger(AppRun.class);

    public static void main(String[] args) {

        try {
            ZooKeeper zooKeeper = ZookeeperClient.connect(CommonConsts.ZOOKEEPER_URL, 5000);
            Properties properties = new Properties();
            properties.setProperty("user","liuxingyi");
            writeData(zooKeeper, CommonConsts.REAL_TIME_PROPERTIES_PATH, getPropertieBytes(properties));
            RealTimeConfigUtils realTimeConfigUtils = RealTimeConfigUtils.getInstances();
            realTimeConfigUtils.load();
            logger.info("get user from realTime : {}", realTimeConfigUtils.getValue("user", null));
            properties.setProperty("user", "liuxingchen");
            writeData(zooKeeper, CommonConsts.REAL_TIME_PROPERTIES_PATH, getPropertieBytes(properties));
            Thread.sleep(20);
            logger.info("get user from realTime update: {}", realTimeConfigUtils.getValue("user", null));
            properties.setProperty("user", "liuxingyan");
            writeData(zooKeeper, CommonConsts.REAL_TIME_PROPERTIES_PATH, getPropertieBytes(properties));
            Thread.sleep(20);
            logger.info("get user from realTime update2: {}", realTimeConfigUtils.getValue("user", null));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] getPropertieBytes(Properties properties){
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<Object, Object> entry : properties.entrySet()) {
            sb.append(entry.getKey()).append("=").append(entry.getValue()).append("\r\n");
        }
        if(StringUtils.isEmpty(sb.toString())){
            return "".getBytes();
        } else {
            return sb.toString().getBytes();
        }
    }

    private static void writeData(ZooKeeper zooKeeper, String path, byte[] data) throws Exception{
        Stat exists = zooKeeper.exists(path, false);
        if(exists == null){
            logger.info("need create node");
            BloomF
            zooKeeper.create(path, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        } else {
            zooKeeper.setData(path, data, -1);
        }
    }
}
